package com.wuyan.locationdog.ui.device


import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.AMap.OnCameraChangeListener
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.CameraPosition
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.PolylineOptions
import com.arcsoft.commonbase.base.BaseBindingActivity
import com.arcsoft.commonbase.ext.customShowLong
import com.arcsoft.commonbase.ext.loadImageCircleCar
import com.blankj.utilcode.util.ClipboardUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.wuyan.locationdog.R
import com.wuyan.locationdog.databinding.TrackDetailActivityBinding
import com.wuyan.locationdog.help.DeviceHelp
import com.wuyan.locationdog.util.HourMinuteConverter
import com.wuyan.locationdog.util.maputil.CustomInfoWindowAdapter
import com.wuyan.locationdog.util.maputil.MapHelp
import com.wuyan.locationdog.util.maputil.MapLifecycle
import com.wuyan.locationdog.viewmodel.DeviceViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class TrackDetailActivity : BaseBindingActivity<TrackDetailActivityBinding>() {
    private var isZoom18: Boolean = false
    private val mViewModel: DeviceViewModel by viewModels()
    val markList: MutableList<Marker> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(MapLifecycle(binding.mapView, savedInstanceState))

    }


    override fun initData() {

        setTitleText("轨迹")

        binding.apply {
            val behavior = BottomSheetBehavior.from(bottomLayout)
            behavior.state = BottomSheetBehavior.STATE_EXPANDED

            mapView.map.setInfoWindowAdapter(CustomInfoWindowAdapter(mActivity))

            imei.text = "设备ID：" + DeviceHelp.selectDeviceBeanContent.imei
            deviceName.text = DeviceHelp.selectDeviceBeanContent.deviceDetailVO.deviceName
            deviceAvatarUrl.loadImageCircleCar(DeviceHelp.selectDeviceBeanContent.deviceDetailVO.deviceAvatarUrl)
            imei.setOnClickListener {
                ClipboardUtils.copyText(DeviceHelp.selectDeviceBeanContent.imei)
                customShowLong("复制成功")
            }

            DeviceHelp.instantTrackBeanContent.apply {
                imei.text = "设备ID：" + DeviceHelp.selectDeviceBeanContent.imei
                deviceName.text = DeviceHelp.selectDeviceBeanContent.deviceDetailVO.deviceName

                val first = posList.first()
                time.text = first.updateTime.substring(0, 10)
                startTime.text = first.updateTime
                //                startAddress.text = first.
                startSpeed.text = first.speed.toString() + "公里/小时"
                val last = posList.last()
                endTime.text = last.updateTime
                endSpeed.text = last.speed.toString() + "公里/小时"


                val latLngs: MutableList<LatLng> = ArrayList()
                val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.track_position)
                val startBitmap = BitmapFactory.decodeResource(resources, R.mipmap.track_position_start)
                val endBitmap = BitmapFactory.decodeResource(resources, R.mipmap.track_position_end)
//                val luBitmap = BitmapFactory.decodeResource(resources, R.mipmap.lu)

                lifecycleScope.launch {
                    delay(500)
                    posList.forEachIndexed { index, pos ->
//                    if (pos.lat > 0 && pos.lng > 0) { }
                        latLngs.add(LatLng(pos.lat, pos.lng))
                        if (index == 0) {

                            mapView.map.addMarker(
                                MarkerOptions().position(LatLng(pos.lat, pos.lng)).anchor(0.5f, 0.5f)
                                    .title(pos.address + "\n" + pos.deviceDataKey.deviceTime)
                                    .icon(BitmapDescriptorFactory.fromBitmap(startBitmap))
                            )
                        } else if (index == posList.size - 1) {

                            mapView.map.addMarker(
                                MarkerOptions().position(LatLng(pos.lat, pos.lng)).anchor(0.5f, 0.5f)
                                    .title(pos.address + "\n" + pos.deviceDataKey.deviceTime)
                                    .icon(BitmapDescriptorFactory.fromBitmap(endBitmap))
                            )
                        } else {
                            //放大18再显示
//                            mapView.map.addMarker(
//                                MarkerOptions().position(LatLng(pos.lat, pos.lng)).anchor(0.5f, 0.5f)
//                                    .title(pos.address + "\n" + pos.deviceDataKey.deviceTime)
//                                    .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
//                            )
                        }
                    }

                    val texture = BitmapDescriptorFactory.fromResource(R.mipmap.lu3)
                    val polyline = mapView.map.addPolyline(
                        PolylineOptions()
                            .addAll(latLngs)
                            .setCustomTexture(texture)
//                            .setCustomTextureIndex(textureIndexs)
                            .setUseTexture(true)
                            .width(48F)
//                            .color(Color.parseColor("#6E4DF3"))
                    )

                    MapHelp.setMapBounds(mapView, latLngs)
                }
                mapView.map.setOnCameraChangeListener(object : OnCameraChangeListener {
                    override fun onCameraChange(p0: CameraPosition) {

                    }

                    override fun onCameraChangeFinish(cameraPosition: CameraPosition) {

                        if (cameraPosition.zoom >= 18) {
                            if (isZoom18) {
                                return
                            }

                            posList.forEachIndexed { index, pos ->
                                if (index == 0) {

                                } else if (index == posList.size - 1) {

                                } else {
                                    //放大18再显示
                                    val mark = mapView.map.addMarker(
                                        MarkerOptions().position(LatLng(pos.lat, pos.lng)).anchor(0.5f, 0.5f)
                                            .title(pos.address + "\n" + pos.deviceDataKey.deviceTime)
                                            .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
                                    )
                                    markList.add(mark)
                                }
                            }


                            isZoom18 = true

                        } else {
                            isZoom18 = false
                            markList.forEach {
                                it.remove()
                            }
                            markList.clear()
                        }
                    }
                })
            }
        }

        val map = HashMap<String, Any>()
        map["imei"] = DeviceHelp.selectDeviceBeanContent.imei
        map["startTime"] = DeviceHelp.startTime
        map["endTime"] = DeviceHelp.endTime
//        mViewModel.deviceLocationRecord(map)

        mViewModel.deviceLocationRecordStatistics(map)
    }

    override fun observe() {
        super.observe()

        mViewModel.statisticsCountBean.observe(this) {
            binding.apply {
                totalmileage.text = it.content.totalMileage.toString() + "km"
                travelDuration.text = HourMinuteConverter.convertToHourMinute(it.content.travelDuration)
            }
        }
//        mViewModel.trackBean.observe(this) {
//            binding.apply {
//                imei.text = "设备ID：" + DeviceHelp.selectDeviceBeanContent.imei
//                deviceName.text = DeviceHelp.selectDeviceBeanContent.deviceDetailVO.deviceName
//
//                val first = it.content.posList.first()
//                time.text = first.updateTime.substring(0, 10)
//                startTime.text = first.updateTime
//                //                startAddress.text = first.
//                startSpeed.text = first.speed.toString() + "公里/小时"
//                val last = it.content.posList.last()
//                endTime.text = last.updateTime
//                endSpeed.text = last.speed.toString() + "公里/小时"
//
//
//                val latLngs: MutableList<LatLng> = ArrayList()
//                it.content.posList.forEachIndexed { index, pos ->
////                    if (pos.lat > 0 && pos.lng > 0) { }
//                    latLngs.add(LatLng(pos.lat, pos.lng))
//                    val startBitmap = BitmapFactory.decodeResource(resources, R.mipmap.track_position_start)
//                    val endBitmap = BitmapFactory.decodeResource(resources, R.mipmap.track_position_end)
//                    val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.track_position)
//                    if (index == 0) {
//                        mapView.map.addMarker(
//                            MarkerOptions().position(LatLng(pos.lat, pos.lng)).anchor(0.5f, 0.5f)
//                                .title("M300云景无线监控设备3")
//                                .icon(BitmapDescriptorFactory.fromBitmap(startBitmap))
//                        )
//                    } else if (index == it.content.posList.size - 1) {
//                        mapView.map.addMarker(
//                            MarkerOptions().position(LatLng(pos.lat, pos.lng)).anchor(0.5f, 0.5f)
//                                .title("M300云景无线监控设备3")
//                                .icon(BitmapDescriptorFactory.fromBitmap(endBitmap))
//                        )
//                    } else {
//                        mapView.map.addMarker(
//                            MarkerOptions().position(LatLng(pos.lat, pos.lng)).anchor(0.5f, 0.5f)
//                                .title("M300云景无线监控设备3")
//                                .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
//                        )
//                    }
//                }
//
//                val polyline = mapView.map.addPolyline(
//                    PolylineOptions()
//                        .addAll(latLngs)
//                        .width(SizeUtils.dp2px(4F).toFloat())
//                        .color(Color.parseColor("#6E4DF3"))
//                )
//                MapHelp.setMapBounds(mapView, latLngs)
//
//
//            }
//        }
    }


    //声明定位回调监听器
    private var mLocationListener = AMapLocationListener { amapLocation ->
        if (amapLocation != null) {
            if (amapLocation.errorCode == 0) {
                //实时位置上报
                Log.e("map", "定位成功:$amapLocation")
                val latLng = LatLng(amapLocation.latitude, amapLocation.longitude)
                binding.mapView.map?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11F))
            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e(
                    "map",
                    "location Error, ErrCode:" + amapLocation.errorCode + ", errInfo:" + amapLocation.errorInfo
                )
            }
        }
    }


}